package com.braveman.im.ui.activity.message;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.braveman.im.R;
import com.braveman.im.bean.LoginBean;
import com.braveman.im.bean.RegisterInfoBean;
import com.braveman.im.bean.RequseForGetCodeBean;
import com.braveman.im.bean.ResponseForGetCodeBean;
import com.braveman.im.constant.Constants;
import com.braveman.im.manager.ApiManager;
import com.braveman.im.thread.ValidateThread;
import com.braveman.im.utils.AppUtils;
import com.braveman.im.utils.UtilsStyle;
import com.braveman.im.utils.ValidateUtils;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.ht.baselibs.utils.UIUtils;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.vondear.rxtools.RxBarTool;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import retrofit2.Call;
import retrofit2.Response;

public class RegisterActivity extends BaseActivity {

    private TextView mGetValidateBtn;
    private EditText mTelView;
    private CheckBox mProtocolCheckbox;
    private EditText mPwdView;
    private EditText mValidateView;
    private CheckBox mSeePwdView;
    private CheckBox mSeePwdViewNext;
    private EditText mPwdViewNext;
    // 弹出框
    private ProgressDialog mDialog;
    private String registerCode;

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void initTitleBar() {
        mTitleBarView.setTitleText("会员注册（1/2）");
    }

    @Override
    protected int initContentView() {
        UtilsStyle.setStatusBarMode(this, true);
        RxBarTool.FlymeSetStatusBarLightMode(getWindow(), true);
        RxBarTool.MIUISetStatusBarLightMode(getWindow(), true);
        return R.layout.activity_register;
    }

    @Override
    protected void initChildView() {
        mTelView = (EditText) findViewById(R.id.et_activity_register_tel);
        mValidateView = (EditText) findViewById(R.id.et_activity_register_validate);
        mPwdView = (EditText) findViewById(R.id.et_activity_register_pwd);
        mPwdViewNext = (EditText) findViewById(R.id.et_activity_register_pwd_next);
        mGetValidateBtn = (TextView) findViewById(R.id.tv_activity_register_get_validate);
        mProtocolCheckbox = (CheckBox) findViewById(R.id.cb_activity_register);
        mSeePwdView = (CheckBox) findViewById(R.id.cb_activity_register_see_pwd);
        mSeePwdViewNext = (CheckBox) findViewById(R.id.cb_activity_register_see_pwd_next);
    }

    @Override
    protected void initChildData() {

    }

    @Override
    protected void setChildViewListener() {
        mSeePwdView.setOnClickListener(this);
        mSeePwdViewNext.setOnClickListener(this);
        mGetValidateBtn.setOnClickListener(this);
        findViewById(R.id.btn_activity_register).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        final String tel = mTelView.getText().toString().trim();
        String code = mValidateView.getText().toString().trim();
        final String pwd = mPwdView.getText().toString().trim();
        String pwdNext = mPwdView.getText().toString().trim();

        switch (v.getId()) {
            case R.id.tv_activity_register_get_validate:
                if (!ValidateUtils.isTelValidate(tel)) return;
                RequseForGetCodeBean requseForGetCodeBean = new RequseForGetCodeBean();
                requseForGetCodeBean.captchaType = "memberRegister";
                requseForGetCodeBean.mobile = tel;
                ApiManager.getApi().getCode(requseForGetCodeBean).enqueue(new NetCallBack<ResponseForGetCodeBean>() {
                    @Override
                    protected void onSuccess(Call<ResponseForGetCodeBean> call, Response<ResponseForGetCodeBean> response) {
                        if (response != null) {
                            ResponseForGetCodeBean responseForGetCodeBean = response.body();
                            if (responseForGetCodeBean != null)
                                registerCode = responseForGetCodeBean.captcha;
                            mValidateView.setText(registerCode);

                        }
                    }
                });
                mGetValidateBtn.setEnabled(false);
                new ValidateThread(mHandler).start();
                mGetValidateBtn.setTextColor(Color.parseColor("#bebebe"));
                break;
            case R.id.btn_activity_register:

                if (!mProtocolCheckbox.isChecked()) {
                    UIUtils.showToast("请同意<服务协议>");
                    return;
                }

                if (TextUtils.isEmpty(tel)) {
                    UIUtils.showToast("请输入手机号码");
                }
                if (!AppUtils.isMobileNO(tel)) {
                    UIUtils.showToast("手机号错误，请重新输入");
                    return;
                }

                if (code.length() == 0) {
                    UIUtils.showToast("请输入验证码");
                    return;
                }

                if (code.length() != 6) {
                    UIUtils.showToast("请输入正确的验证码");
                    return;
                }
                if (!ValidateUtils.isPwdValidate(pwd)) return;
                if (!pwd.equals(pwdNext)) {
                    UIUtils.showToast("两次密码不一致，请重新输入");
                    return;
                }
//                signUp();
                final RegisterInfoBean registerInfoBean = new RegisterInfoBean();
                registerInfoBean.captcha = registerCode;
                registerInfoBean.password = pwd;
                registerInfoBean.mobile = tel;
                showLoadingDialog();
                ApiManager.getApi().registerInfor(registerInfoBean).enqueue(new NetCallBack<RegisterInfoBean>() {
                    @Override
                    protected void onSuccess(Call<RegisterInfoBean> call, Response<RegisterInfoBean> response) {
                        Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_LONG).show();
                        Bundle bundle = new Bundle();
                        RegisterInfoBean registerInfoBean1 = response.body();

                        LoginBean loginBean = new LoginBean();
                        loginBean.identifier = tel;
                        loginBean.identityType = "mobile";
                        loginBean.password = pwd;
                        ApiManager.getApi().login(loginBean).enqueue(new NetCallBack<LoginBean>() {
                            @Override
                            protected void onSuccess(Call<LoginBean> call, Response<LoginBean> response) {
                                LoginBean loginBean1 = response.body();
                                SharedPreferencesUtils.put(Constants.TOKEN, loginBean1.token);
                                UIUtils.showToast("服务器登录成功");
                            }

                            @Override
                            protected void hiddenProgress() {
                                hideLodingDialog();
                            }
                        });
                        bundle.putString("user_id", registerInfoBean1.id);
                        bundle.putString("userName", tel);
                        bundle.putString("passWord", pwd);
                        ActivityUtils.startActivityAndFinish(RegisterActivity.this, RegisterNextActivity.class, bundle);
                    }
                });
                break;
            case R.id.cb_activity_register_see_pwd:
                if (mSeePwdView.isChecked()) {
                    mPwdView.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    mPwdView.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                break;
            case R.id.cb_activity_register_see_pwd_next:
                if (mSeePwdViewNext.isChecked()) {
                    mPwdViewNext.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    mPwdViewNext.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                break;
        }
    }

    @Override
    protected void handleMessage(BaseActivity context, Message msg) {
        switch (msg.what) {
            case 100:
                mGetValidateBtn.setText(msg.obj.toString());
                break;
            case 200:
                mGetValidateBtn.setTextColor(Color.parseColor("#6284dd"));
                mGetValidateBtn.setText("获取验证码");
                mGetValidateBtn.setEnabled(true);
                break;
        }
    }

    /**
     * 匹配正则表达式
     *
     * @param str
     * @return
     */
    public static String stringFilter(String str) throws PatternSyntaxException {
        // 只允许字母、数字和汉字-
        //String   regEx  =  "[^a-zA-Z0-9-u4E00-u9FA5]";
        String regEx = "[^a-zA-Z0-9\u4e00-\u9fa5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * 注册方法
     */
    private void signUp() {
        // 注册是耗时过程，所以要显示一个dialog来提示下用户
        mDialog = new ProgressDialog(this);
        mDialog.setMessage("注册中，请稍后...");
        mDialog.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final String username = mTelView.getText().toString().trim();
                    String password = mPwdView.getText().toString().trim();
                    EMClient.getInstance().createAccount(username, password);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (!RegisterActivity.this.isFinishing()) {
                                mDialog.dismiss();
                            }
                            Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_LONG).show();
                            Bundle bundle = new Bundle();
                            bundle.putString("user_id", username);
                            ActivityUtils.startActivityAndFinish(RegisterActivity.this, RegisterNextActivity.class, bundle);
                        }
                    });
                } catch (final HyphenateException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (!RegisterActivity.this.isFinishing()) {
                                mDialog.dismiss();
                            }
                            /**
                             * 关于错误码可以参考官方api详细说明
                             * http://www.easemob.com/apidoc/android/chat3.0/classcom_1_1hyphenate_1_1_e_m_error.html
                             */
                            int errorCode = e.getErrorCode();
                            String message = e.getMessage();
                            Log.d("lzan13", String.format("sign up - errorCode:%d, errorMsg:%s", errorCode, e.getMessage()));
                            switch (errorCode) {
                                // 网络错误
                                case EMError.NETWORK_ERROR:
                                    Toast.makeText(RegisterActivity.this, "网络错误 code: " + errorCode + ", message:" + message, Toast.LENGTH_LONG).show();
                                    break;
                                // 用户已存在
                                case EMError.USER_ALREADY_EXIST:
                                    Toast.makeText(RegisterActivity.this, "用户已存在 code: " + errorCode + ", message:" + message, Toast.LENGTH_LONG).show();
                                    break;
                                // 参数不合法，一般情况是username 使用了uuid导致，不能使用uuid注册
                                case EMError.USER_ILLEGAL_ARGUMENT:
                                    Toast.makeText(RegisterActivity.this, "参数不合法，一般情况是username 使用了uuid导致，不能使用uuid注册 code: " + errorCode + ", message:" + message, Toast.LENGTH_LONG).show();
                                    break;
                                // 服务器未知错误
                                case EMError.SERVER_UNKNOWN_ERROR:
                                    Toast.makeText(RegisterActivity.this, "服务器未知错误 code: " + errorCode + ", message:" + message, Toast.LENGTH_LONG).show();
                                    break;
                                case EMError.USER_REG_FAILED:
                                    Toast.makeText(RegisterActivity.this, "账户注册失败 code: " + errorCode + ", message:" + message, Toast.LENGTH_LONG).show();
                                    break;
                                default:
                                    Toast.makeText(RegisterActivity.this, "ml_sign_up_failed code: " + errorCode + ", message:" + message, Toast.LENGTH_LONG).show();
                                    break;
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
